{# SPDX-FileCopyrightText: © 2014-2017 Siemens AG

   SPDX-License-Identifier: FSFAP
#}

function createTableBase{{ table.type }}(activated) {
  var aoColumns = [
      { "sTitle": "{{ 'Count'| trans }}", "sClass": "right read_only", "sWidth": "5%" },
      { "sTitle": "{{ table.description }}", "sClass": "left"}
    ]
  if (activated)
  {
    var id = '#copyright{{ table.type }}';
    var action = 'getData'
    aoColumns = aoColumns.concat([
      { "sTitle": "", "sClass": "center read_only", "sWidth": "10%", "bSortable": false },
      { "sTitle": "<input type='checkbox' name='selectDelete{{ table.type }}' id='selectDelete{{ table.type }}' style='margin-left:47.5%'>", "sClass": "center read_only", "sWidth": "10%", "bSortable": false }
    ]);
  }
  else
  {
    var id = '#copyright{{ table.type }}deactivated';
    var action = 'getDeactivatedData'
    aoColumns = aoColumns.concat([
      { "sTitle": "", "sClass": "center read_only", "sWidth": "10%", "bSortable": false },
      { "sTitle": "<input type='checkbox' name='selectUndo{{ table.type }}' id='selectUndo{{ table.type }}' style='margin-left:47.5%'>", "sClass": "center read_only", "sWidth": "10%", "bSortable": false }
    ]);
  }

  return $(id).dataTable({
    "bServerSide": true,
    "sAjaxSource": "?mod=ajax-copyright-hist&action=" + action,
    "fnServerData": function (sSource, aoData, fnCallback) {
      aoData.push({ "name":"upload", "value": "{{ table.uploadId }}" });
      aoData.push({ "name":"item", "value": "{{ table.uploadTreeId }}" });
      aoData.push({ "name":"agent", "value": "{{ table.agentId }}" });
      aoData.push({ "name":"type", "value": "{{ table.type }}" });
      aoData.push({ "name":"filter", "value": "{{ table.filter }}" });
      if(activated)
      {
        if($('#inverseSearchActivated{{table.type}}').is(':checked'))
        {
          aoData.push( { "name":"isInverse", "value": "true"} );
        } else {
          aoData.push( { "name":"isInverse", "value": "false" } );
        }
      } else {
        if($('#inverseSearchDeactivated{{table.type}}').is(':checked'))
        {
          aoData.push( { "name":"isInverse", "value": "true"} );
        } else {
          aoData.push( { "name":"isInverse", "value": "false" } );
        }
      }
      
      $.getJSON(sSource, aoData, fnCallback).fail(function() {
        if (confirm("You are not logged in. Go to login page?"))
          window.location.href = "?mod=auth";
      });
    },
    "sPaginationType": "listbox",
    "lengthMenu": [10, 25, 50, 75, 100, 200, 500, 1000],
    "aoColumns": aoColumns,
    "aaSorting": {{ table.sorting }},
    "iDisplayLength": 50,
    "bProcessing": true,
    "bStateSave": true,
    "bRetrieve": true
  });
}

function createTable{{ table.type }}() {
  var enabledTable = createTableBase{{ table.type }}(true).makeEditable({
    "sReadOnlyCellClass": "read_only",
    "sSelectedRowClass": "selectedRow",
    "sUpdateURL": "?mod=ajax-copyright-hist&action=update&type={{ table.type }}",
    "fnOnEditing": function(aInput) {
      var value = aInput[0].value;
      var isValid = (value) && !(/^\s*$/.test(value));
      if (isValid) {
        var id = aInput.parents("tr:first")[0].id;
        var hash = id.split(",")[2];
        $("#delete{{ table.type }}" + hash).hide();
        var updateElement = $("#update{{ table.type }}" + hash);
        updateElement.text("updating...");
        updateElement.show();
      }
      return isValid;
    },
    "sSuccessResponse": "success"
  });

  createTableBase{{ table.type }}(false);

  $('#selectDelete{{ table.type }}').change(function () {
    $('.deleteBySelect{{ table.type }}').prop('checked', $(this).prop("checked"));
  });

  $('#deleteSelected{{ table.type }}').click(function () {
    $("input:checkbox[class=deleteBySelect{{ table.type }}]:checked").each(function () {
      currentValue = $(this).val();
      var currUploadData = currentValue.split(',');
      delete{{ table.type }}(currUploadData[0], currUploadData[1], currUploadData[2], currUploadData[3]);
    });
  });

  $('#selectUndo{{ table.type }}').change(function () {
    $('.undoBySelect{{ table.type }}').prop('checked', $(this).prop("checked"));
  });

  $('#undoSelected{{ table.type }}').click(function () {
    $("input:checkbox[class=undoBySelect{{ table.type }}]:checked").each(function () {
      currentValue = $(this).val();
      var currUploadData = currentValue.split(',');
      undo{{ table.type }}(currUploadData[0], currUploadData[1], currUploadData[2], currUploadData[3]);
    });
  });

  $('#replaceSelected{{ table.type }}').click(function () {
    var replaceText = $('#replaceText{{ table.type }}').val().trim();
    var replaceIsValid = (replaceText) && !(/^\s*$/.test(replaceText));
    var ajaxList = new Array();
    if (replaceIsValid) {
      var regex = advanceSearchToRegex($('#advSearchText{{ table.type }}').val().trim());
      $("input:checkbox[class=deleteBySelect{{ table.type }}]:checked").each(function () {
        var currentId = $(this).val();
        var currUploadData = currentId.split(',');
        var currentValue = enabledTable.api().row($(this).parent().parent()[0]).data()[1];
        currentValue = $("<textarea/>").html(currentValue).text();  // Decode HTML &lt; &gt;
        var newValue = replaceText;
        if (!/^\s*$/.test(regex)) {
          newValue = currentValue.replace(new RegExp(regex, "gi"), replaceText);
        }
        ajaxList.push(updateRows{{ table.type }}(currUploadData[0],
          currUploadData[1], currUploadData[2], currUploadData[3], newValue));
      });
      // Wait for all ajax calls to resolve
      $.when.apply($, ajaxList).done(function(){
        location.reload(true)
      });
    }
  });

  $('#copyright{{ table.type }} tbody').on('click', 'tr td:nth-child(3)', function (event) {
    if ($(this).find('img:visible').length > 0) {
      if ($(event.target).is('img')) {
        return;
      }
      var currentValue = $(this).closest('tr').attr('id');
      var currUploadData = currentValue.split(',');
      delete{{ table.type }}(currUploadData[0], currUploadData[1], currUploadData[2], currUploadData[3]);
    } else if ($(this).find('span[id^="update"]:visible').length > 0) {
      if ($(event.target).closest('a').length > 0) {
        return;
      }
      var currentValue = $(this).closest('tr').attr('id');
      var currUploadData = currentValue.split(',');
      undo{{ table.type }}(currUploadData[0], currUploadData[1], currUploadData[2], currUploadData[3]);
    }
  });

  $('#copyright{{ table.type }} tbody').on('click', 'tr td:nth-child(4)', function (event) {
    if ($(event.target).is('input')) {
      return;
    }
    var $checkbox = $(this).find('input[type="checkbox"]');
    $checkbox.prop('checked', !$checkbox.prop('checked')).trigger('change');
  });

  return enabledTable;
}

function createPlaneTableBase{{ table.type }}(activated) {
  var aoColumns = [
      { "sTitle": "{{ 'Count'| trans }}", "sClass": "right read_only", "sWidth": "5%" },
      { "sTitle": "{{ table.description }}", "sClass": "left"},
      { "sTitle": "", "sClass": "center read_only", "sWidth": "10%", "bSortable": false }
    ];
  if (activated)
  {
    var id = '#copyright{{ table.type }}';
    var action = 'getData'
    aoColumns = aoColumns.concat([
      { "sTitle": "<input type='checkbox' name='selectDelete{{ table.type }}' id='selectDelete{{ table.type }}' style='margin-left:11px'>", "sClass": "center read_only", "sWidth": "5%", "bSortable": false }
    ]);
  }
  else
  {
    var id = '#copyright{{ table.type }}deactivated';
    var action = 'getDeactivatedData'
    aoColumns = aoColumns.concat([
      { "sTitle": "<input type='checkbox' name='selectUndo{{ table.type }}' id='selectUndo{{ table.type }}' style='margin-left:11px'>", "sClass": "center read_only", "sWidth": "5%", "bSortable": false }
    ]);
  }

  return $(id).dataTable({
    "bServerSide": true,
    "sAjaxSource": "?mod=ajax-copyright-hist&action=" + action,
    "fnServerData": function (sSource, aoData, fnCallback) {
      aoData.push({ "name":"upload", "value": "{{ table.uploadId }}" });
      aoData.push({ "name":"item", "value": "{{ table.uploadTreeId }}" });
      aoData.push({ "name":"type", "value": "{{ table.type }}" });
      aoData.push({ "name":"filter", "value": "{{ table.filter }}" });
      $.getJSON(sSource, aoData, fnCallback).fail(function() {
        if (confirm("You are not logged in. Go to login page?"))
          window.location.href = "?mod=auth";
      });
    },
    "sPaginationType": "listbox",
    "lengthMenu": [10, 25, 50, 75, 100, 200, 500, 1000],
    "aoColumns": aoColumns,
    "aaSorting": {{ table.sorting }},
    "iDisplayLength": 50,
    "bProcessing": true,
    "bStateSave": true,
    "bRetrieve": true
  });
}

function createPlainTable{{ table.type }}() {
  var enabledTable = createPlaneTableBase{{ table.type }}(true);
  createPlaneTableBase{{ table.type }}(false);

  $('#selectDelete{{ table.type }}').change(function () {
    $('.deleteBySelect{{ table.type }}').prop('checked', $(this).prop("checked"));
  });

  $('#deleteSelected{{ table.type }}').click(function () {
    $("input:checkbox[class=deleteBySelect{{ table.type }}]:checked").each(function () {
      currentValue = $(this).val();
      var currUploadData = currentValue.split(',');
      deleteHashDecision(currUploadData[0], currUploadData[1], currUploadData[2]);
    });
  });

  $('#selectUndo{{ table.type }}').change(function () {
    $('.undoBySelect{{ table.type }}').prop('checked', $(this).prop("checked"));
  });

  $('#undoSelected{{ table.type }}').click(function () {
    $("input:checkbox[class=undoBySelect{{ table.type }}]:checked").each(function () {
      currentValue = $(this).val();
      var currUploadData = currentValue.split(',');
      undoHashDecision(currUploadData[0], currUploadData[1], currUploadData[2]);
    });
  });

  $('#searchReplaceTable{{ table.type }}').remove();
  $('#testVal{{ table.type }}').remove();
  $('#testReplacement{{ table.type }}').remove();
  $('#replaceSelected{{ table.type }}').remove();

  return enabledTable;
}

function updateRows{{ table.type }}(upload, item, hash, kind, replaceText) {
  return $.ajax({
    type: 'POST',
    dataType: 'text',
    url: '?mod=ajax-copyright-hist&action=update&type={{ table.type }}',
    data: { id : upload + ',' + item + ',' + hash + ',' + kind, value : replaceText },
    success: function(data) {
      var updateElement = $("#update{{ table.type }}" + hash);
      $("#delete{{ table.type }}" + hash).hide();
      updateElement.html("updating...");
    },
    error: function(errorResponse) {
      alert(errorResponse.responseText);
    }
  });
}

function delete{{ table.type }}(upload, item, hash, kind) {
  $.ajax({
    type: 'POST',
    dataType: 'text',
    url: '?mod=ajax-copyright-hist&action=delete&type={{ table.type }}',
    data: { id : upload + ',' + item + ',' + hash + ',' + kind },
      success: function(data) {
        $("#delete{{ table.type }}" + hash).hide();
        $("#update{{ table.type }}" + hash).attr("style","display:inline !important;");
        $("tr.row"+hash+" td").attr("style","background-color:#fdff32 !important");
      },
      error: function(errorResponse) {
        alert(errorResponse.responseText);
      }
  });
}

function undo{{ table.type }}(upload, item, hash, kind) {
  $.ajax({
    type: 'POST',
    dataType: 'text',
    url: '?mod=ajax-copyright-hist&action=undo',
    data: { id : upload + ',' + item + ',' + hash + ',' + kind },
      success: function(data) {
        $("#delete{{ table.type }}" + hash).show();
        $("#update{{ table.type }}" + hash).hide();
        $("#deleteBySelect{{ table.type }}" + hash).prop('checked', false);
        $("tr.row"+hash+" td").attr("style","background-color:''");
      },
      error: function(errorResponse) {
        alert(errorResponse.responseText);
      }
  });
}
